import { defineStore } from 'pinia';
import localforage from 'localforage';
import {store} from "@/store";

export const useIndexedDBStore = defineStore('indexedDB', {
  state: () => ({
    courseDB: localforage.createInstance({
      name: 'courseDB',
      size: 1024 * 5
    }),
    pointDB: localforage.createInstance({
      name: 'pointDB',
      size: 1024 * 400
    }),
    studentAndMacDB: localforage.createInstance({
      name: 'studentAndMacDB',
      size: 1024 * 10
    }),
  }),
  actions: {
    setCourseDB(key: string, value: any) {
      this.courseDB.setItem(key, value);
    },
    async setPointDB(key: string, value: any) {
      await this.pointDB.setItem(key, value);
    },
    getPointDB(key: string) {
      return new Promise(async (resolve, reject) => {
        try {
          const value = await this.pointDB.getItem(key);
          resolve(value);
        } catch (err) {
          reject(err);
        }
      })
    },
    removePointDB(key: string) {
      return new Promise(async (resolve, reject) => {
        try {
          const value = await this.pointDB.removeItem(key);
          resolve(value);
        } catch (err) {
          reject(err);
        }
      })
    },
    clearPointDB() {
      return new Promise(async (resolve, reject) => {
        try {
          const value = await this.pointDB.clear();
          resolve(value);
        } catch (err) {
          reject(err);
        }
      })
    },
    setStudentAndMacDB(key: string, value: any) {
      this.studentAndMacDB.setItem(key, value);
    },
  },
});
export function useIndexedDB() {
  return useIndexedDBStore(store);
}
